package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.pojo.AdminUsers;
import com.neudu.glsb.pojo.Employees;
import com.neudu.glsb.pojo.Menus;
import com.neudu.glsb.pojo.Roles;
import com.neudu.glsb.service.AdminUsersService;
import com.neudu.glsb.service.EmployeesService;
import com.neudu.glsb.service.MenusService;
import com.neudu.glsb.utils.TokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.List;

@RestController
public class AdminUserController {

    @Autowired
    private AdminUsersService adminUsersService;
    @Autowired
    private EmployeesService employeesService;
    @Autowired
    private MenusService menusService;
    @Autowired
    private JSONReturn jsonReturn;
    @Autowired
    private TokenUtils tokenUtils;
 @PostMapping("login")
  public String login(@RequestParam String loginMethod, @RequestParam String identifier, @RequestParam String password, @RequestParam String captcha, HttpServletRequest request) {
    try {
        String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
        if (!captcha.equalsIgnoreCase(sessionCaptcha)) {
            return jsonReturn.returnFailed("验证码错误");
        }
        LambdaQueryWrapper<AdminUsers> queryWrapper = new LambdaQueryWrapper<>();
        if ("username".equals(loginMethod)) {
            queryWrapper.eq(AdminUsers::getUsername, identifier);
        } else if ("email".equals(loginMethod)) {
            queryWrapper.eq(AdminUsers::getEmail, identifier);
        } else if ("phone".equals(loginMethod)) {
            queryWrapper.eq(AdminUsers::getEmail, identifier); // 假设email字段存储的是手机号
        } else {
            return jsonReturn.returnFailed("无效的登录方式");
        }
        queryWrapper.eq(AdminUsers::getPassword, password)
                .select(AdminUsers::getId, AdminUsers::getRoleId, AdminUsers::getEmail, AdminUsers::getUsername, AdminUsers::getLoginMethod);
        List<AdminUsers> users = adminUsersService.list(queryWrapper);

        if (users != null && users.size() > 0) {
            AdminUsers loginUser = users.get(0);
            String token = tokenUtils.getToken();
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", token);
            responseData.put("roleId", loginUser.getRoleId());
            responseData.put("adminUserId", loginUser.getId()); // 返回 adminUserId
            return jsonReturn.returnSuccess(responseData);
        } else {
            return jsonReturn.returnFailed("用户名或密码错误");
        }
    } catch (IOException e) {
        return jsonReturn.returnError("登录过程中出现异常：" + e.getMessage());
    }
}
//    @GetMapping("/captcha")
//    public ResponseEntity<String> generateCaptcha(HttpServletRequest request) {
//        try {
//            // 创建 BufferedImage
//            int width = 120;
//            int height = 40;
//            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
//            Graphics2D g2d = image.createGraphics();
//
//            // 设置背景颜色
//            g2d.setColor(Color.WHITE);
//            g2d.fillRect(0, 0, width, height);
//
//            // 生成随机验证码
//            Random random = new Random();
//            String captcha = random.ints(48, 123)
//                    .filter(i -> (i >= 48 && i <= 57) || (i >= 65 && i <= 90) || (i >= 97 && i <= 122))
//                    .limit(6)
//                    .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
//                    .toString();
//
//            // 将验证码存入 session
//            request.getSession().setAttribute("captcha", captcha);
//
//            // 设置字体
//            g2d.setFont(new Font("Arial", Font.BOLD, 24));
//            g2d.setColor(Color.BLACK);
//
//            // 绘制验证码
//            for (int i = 0; i < captcha.length(); i++) {
//                char c = captcha.charAt(i);
//                g2d.drawString(String.valueOf(c), 10 + i * 18, 28);
//            }
//
//            // 添加干扰线
//            for (int i = 0; i < 5; i++) {
//                g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
//                g2d.drawLine(random.nextInt(width), random.nextInt(height), random.nextInt(width), random.nextInt(height));
//            }
//
//            // 添加噪点
//            for (int i = 0; i < 30; i++) {
//                g2d.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
//                g2d.drawOval(random.nextInt(width), random.nextInt(height), 1, 1);
//            }
//
//            g2d.dispose();
//
//            // 转换为 Base64
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            javax.imageio.ImageIO.write(image, "png", baos);
//            String base64 = Base64.getEncoder().encodeToString(baos.toByteArray());
//
//            return ResponseEntity.ok(base64);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonReturn.returnError(e.getMessage()));
//        }
//    }
@GetMapping("/captcha")
public ResponseEntity<String> generateCaptcha(HttpServletRequest request) {
    try {
        // 图片尺寸
        int width = 140;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = image.createGraphics();

        // 抗锯齿设置，文字更平滑
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 白色背景
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, width, height);

        // 生成随机数字（1-9）
        Random random = new Random();
        int num1 = random.nextInt(9) ;
        int num2 = random.nextInt(9) ;
        int result = num1 + num2;
        request.getSession().setAttribute("captcha", String.valueOf(result));

        // 字体设置（常规粗细，适中大小）
        Font font = new Font("Arial", Font.PLAIN, 26);
        g2d.setFont(font);
        FontMetrics metrics = g2d.getFontMetrics(font);

        // 计算垂直居中基线（确保所有元素上下居中）
        int baseY = (height - metrics.getHeight()) / 2 + metrics.getAscent();

        // 绘制第一个数字（随机深色）
        int num1R = random.nextInt(150);
        int num1G = random.nextInt(150);
        int num1B = random.nextInt(150);
        g2d.setColor(new Color(num1R, num1G, num1B));
        String num1Str = String.valueOf(num1);
        int num1X = 15; // 左侧起始位置
        g2d.drawString(num1Str, num1X, baseY);

        // 绘制加号（独立随机色）
        int plusR = random.nextInt(180);
        int plusG = random.nextInt(180);
        int plusB = random.nextInt(180);
        g2d.setColor(new Color(plusR, plusG, plusB));
        int plusX = num1X + metrics.stringWidth(num1Str) + 10; // 与数字间距
        g2d.drawString("+", plusX, baseY);

        // 绘制第二个数字（另一随机深色）
        int num2R = random.nextInt(150);
        int num2G = random.nextInt(150);
        int num2B = random.nextInt(150);
        g2d.setColor(new Color(num2R, num2G, num2B));
        String num2Str = String.valueOf(num2);
        int num2X = plusX + metrics.stringWidth("+") + 10; // 与加号间距
        g2d.drawString(num2Str, num2X, baseY);

        // 绘制等号（随机色）
        int equalR = random.nextInt(180);
        int equalG = random.nextInt(180);
        int equalB = random.nextInt(180);
        g2d.setColor(new Color(equalR, equalG, equalB));
        int equalX = num2X + metrics.stringWidth(num2Str) + 10; // 与数字间距
        g2d.drawString("=", equalX, baseY);

        // 添加干扰线（浅色系）
        for (int i = 0; i < 3; i++) {
            g2d.setColor(new Color(random.nextInt(200) + 55, random.nextInt(200) + 55, random.nextInt(200) + 55));
            g2d.drawLine(
                    random.nextInt(width / 4), random.nextInt(height),
                    width - random.nextInt(width / 4), random.nextInt(height)
            );
        }

        // 添加噪点
        for (int i = 0; i < 30; i++) {
            g2d.setColor(new Color(random.nextInt(180) + 75, random.nextInt(180) + 75, random.nextInt(180) + 75));
            g2d.fillOval(random.nextInt(width), random.nextInt(height), 2, 2);
        }

        g2d.dispose();

        // 转换为Base64
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        javax.imageio.ImageIO.write(image, "png", baos);
        String base64 = Base64.getEncoder().encodeToString(baos.toByteArray());

        return ResponseEntity.ok(base64);
    } catch (Exception e) {
        e.printStackTrace();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonReturn.returnError(e.getMessage()));
    }
}

    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String password,
                           @RequestParam String email,
                           @RequestParam Integer role_id,
                           @RequestParam String captcha,
                           HttpServletRequest request) {
        try {
            String sessionCaptcha = (String) request.getSession().getAttribute("captcha");
            if (!captcha.equalsIgnoreCase(sessionCaptcha)) {
                return jsonReturn.returnFailed("验证码错误");
            }

            AdminUsers user = new AdminUsers();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setRoleId(role_id);
            user.setLoginMethod("password");
            boolean save = adminUsersService.save(user);
            if (save) {
                return jsonReturn.returnSuccess("注册成功");
            } else {
                return jsonReturn.returnFailed("注册失败");
            }
        } catch (Exception e) {
            return jsonReturn.returnError("注册过程中出现异常：" + e.getMessage());
        }
    }


    @PostMapping("/getmenus")
    public ResponseEntity<String> getMenusByRoleId(@RequestBody Map<String, Integer> requestBody) {
        try {
            Integer roleid = requestBody.get("roleid");
            if (roleid == null) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(jsonReturn.returnError("Invalid roleid"));
            }
            List<Menus> menus = menusService.getByroleid(roleid);
            // 检查数据是否包含“员工管理”及其子菜单
            // 如果需要，可以添加日志输出menus的内容进行调试
            return ResponseEntity.ok(jsonReturn.returnSuccess(menus));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(jsonReturn.returnError(e.getMessage()));
        }
    }

    @GetMapping("/all-accounts")
    public String getAllAccounts() {
        try {
            // 这里需要根据业务逻辑查询关联的员工姓名
            List<Map<String, Object>> accounts = adminUsersService.getAllAccounts();
            return jsonReturn.returnSuccess(accounts);
        } catch (Exception e) {
            return jsonReturn.returnError("获取账号信息失败：" + e.getMessage());
        }
    }

    // 获取未分配账号的员工列表
//    @GetMapping("/unassigned-employees")
//    public List<Employees> getUnassignedEmployees() {
//        return employeesService.getUnassignedEmployees();
//    }
    @GetMapping("/unassigned-employees")
    public String getUnassignedEmployees() {
        try {
            List<Employees> unassignedEmployees = employeesService.getUnassignedEmployees();
            return jsonReturn.returnSuccess(unassignedEmployees);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取未分配账号的员工列表失败：" + e.getMessage());
        }
    }


    // 分配账号
    @PostMapping("/assign-account")
    public String assignAccount(@RequestBody Map<String, Object> request) {
        try {
            if (!request.containsKey("employeeId") || request.get("employeeId") == null) {
                return jsonReturn.returnError("必须选择员工");
            }

            boolean success = adminUsersService.assignAccount(request);
            return success ? jsonReturn.returnSuccess()
                    : jsonReturn.returnError("账号分配失败");
        } catch (Exception e) {
            return jsonReturn.returnError(e.getMessage());
        }
    }

    // 更改密码
    // 更改密码
//    @PostMapping("/change-password")
//    public String changePassword(@RequestParam("userId") Integer userId,
//                                 @RequestParam("newPassword") String newPassword) {
//        try {
//            AdminUsers adminUser = adminUsersService.getById(userId);
//            if (adminUser == null) {
//                return jsonReturn.returnFailed("用户不存在");
//            }
//            adminUser.setPassword(newPassword);
//            boolean update = adminUsersService.updateById(adminUser);
//            if (update) {
//                return jsonReturn.returnSuccess("密码更改成功");
//            } else {
//                return jsonReturn.returnFailed("密码更改失败");
//            }
//        } catch (Exception e) {
//            return jsonReturn.returnError("密码更改过程中出现异常：" + e.getMessage());
//        }
//    }
    @PostMapping("/change-password")
    public String changePassword(@RequestBody Map<String, Object> requestBody) {
        try {
            Integer userId = (Integer) requestBody.get("userId");
            String newPassword = (String) requestBody.get("newPassword");

            // 校验参数
            if (userId == null || newPassword == null) {
                return jsonReturn.returnFailed("缺少必要的参数");
            }

            // 查询用户是否存在
            AdminUsers adminUser = adminUsersService.getById(userId);
            if (adminUser == null) {
                return jsonReturn.returnFailed("用户不存在");
            }

            // 更新密码
            adminUser.setPassword(newPassword);
            boolean update = adminUsersService.updateById(adminUser);

            if (update) {
                return jsonReturn.returnSuccess("密码更改成功");
            } else {
                return jsonReturn.returnFailed("密码更改失败");
            }
        } catch (Exception e) {
            // 捕获所有异常并返回友好的错误响应
            // 避免直接暴露底层错误信息
            return jsonReturn.returnError("密码更改过程中出现异常，请联系管理员");
        }
    }
}





